﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.SeedWeaningCommand;
using MediatR;

namespace I_Produce.Read.API.Application.CommandHandlers.SeedWeaningHandler
{
	public class SeedWeaningQueryCommandHandler : IRequestHandler<SeedWeaningQueryCommand, ApiResult<PagerResult<SeedWeaning>>>
	{
		private readonly ISeedWeaningRepository _repository;

		public SeedWeaningQueryCommandHandler(ISeedWeaningRepository repository)
		{
			_repository = repository;
		}

		public async Task<ApiResult<PagerResult<SeedWeaning>>> Handle(SeedWeaningQueryCommand request, CancellationToken cancellationToken)
		{
			var list = _repository.All().Result.Where(x => !x.IsDel);

			if (!string.IsNullOrEmpty(request.sWeaningDate))
			{
				list = list.Where(x => x.WeaningDate >= DateTime.Parse(request.sWeaningDate));
			}

			if (!string.IsNullOrEmpty(request.eWeaningDate))
			{
				list = list.Where(x => x.WeaningDate < DateTime.Parse(request.eWeaningDate).AddDays(1));
			}

			if (!string.IsNullOrEmpty(request.auricle))
			{
				list = list.Where(x => x.Auricle.Contains(request.auricle));
			}

			if (!string.IsNullOrEmpty(request.personCharge))
			{
				list = list.Where(x => x.PersonCharge.Equals(request.personCharge));
			}

			if (!string.IsNullOrEmpty(request.transferBuilding))
			{
				list = list.Where(x => x.TransferBuilding.Contains(request.transferBuilding));
			}

			var total = list.Count();
			var page = (int)Math.Ceiling(total * 1.0 / request.pageSize);

			list = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

			return new ApiResult<PagerResult<SeedWeaning>>
			{
				Code = 200,
				msg = "成功",
				Data = new PagerResult<SeedWeaning>
				{
					TotalCount = total,
					PageCount = page,
					Datas = list.ToList()
				}
			};
		}
	}
}
